package servlet;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import factory.DAOFactory;
import test.MD5;
import vo.Person;


public class PersonServlet extends HttpServlet {

    public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException {
    	this.doPost(req, resp);
    }
    
    public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
    	resp.setCharacterEncoding("utf-8");
    	req.setCharacterEncoding("utf-8");
    	String path = null;
    	String status = req.getParameter("status");
    	if(status!=null) {
    		if("login".equals(status)) {
		    	String id = req.getParameter("id");
		    	String password = req.getParameter("password");
//		    	try {
//					password = MD5.generateCode(password);
//				} catch (Exception e1) {
//					e1.printStackTrace();
//				}
		    	Person person = new Person();
		    	person.setUserId(id);
		    	person.setUserPwd(password);
		    	try {
					if(DAOFactory.getPersonDaoInstance().login(person)) {
						req.getSession().setAttribute("uid", person.getUid());
						req.getSession().setAttribute("uname", person.getUserName());
						req.getSession().setAttribute("sex", person.getUserSex());
						path = "login_success.jsp";
					}
					else {
						ServletContext context = this.getServletContext();
						context.setAttribute("err", "login failed,username or password is not Correct");
						path="login.jsp";
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
    		}
    		
    		if("register".equals(status)) {
    			boolean flag = false;
    			String id = req.getParameter("id");
		    	String password = req.getParameter("password");
		    	String name = req.getParameter("name");
		    	String sex = req.getParameter("sex");
		    	String phone = req.getParameter("phone");
		    	String email = req.getParameter("email");
		    	try {
//					password = MD5.generateCode(password);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
		    	Person person = new Person();
		    	person.setUserId(id);
		    	person.setUserPwd(password);
		    	person.setUserName(name);
		    	person.setUserSex(sex);
		    	person.setUPhone(phone);
		    	person.setUEmail(email);
		    	try {
		    		DAOFactory.getPersonDaoInstance().insert(person);
		    		flag = true;
		    	}catch(Exception e) {
		           e.printStackTrace();
		    	}
		    	req.setAttribute("flag", flag);
		    	path="register_do.jsp";
    		}
    			
    		}else {
    			path = "error01.jsp";
    		}
    		
		    req.getRequestDispatcher(path).forward(req, resp);
    }
}
